package com.ruoyi.biz.service;

import java.math.BigDecimal;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.biz.domain.BizTopicFollow;
import com.ruoyi.biz.mapper.BizTopicFollowMapper;
import com.ruoyi.biz.model.req.BizTopicReq;
import com.ruoyi.biz.model.resp.BizTopicResp;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;

import java.util.stream.Collectors;

import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.biz.mapper.BizTopicMapper;
import com.ruoyi.biz.domain.BizTopic;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import static com.ruoyi.common.utils.SecurityUtils.getUserId;
import static com.ruoyi.common.utils.SecurityUtils.isAll;


/**
 * 子课题Service业务层处理
 *
 * @author tianl
 * @date 2024-12-30
 */
@Service
public class BizTopicService extends ServiceImpl<BizTopicMapper, BizTopic> {
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private BizTopicFollowMapper bizTopicFollowMapper;

    /**
     * 分页查询子课题
     */
    public IPage<BizTopicResp> listPage(BizTopicReq req) {
        req.getParams().put("userId", isAll() ? "1" : getUserId());
        IPage<BizTopicResp> page = baseMapper.list(PageUtils.page(), req);
        List<Long> parentIds = page.getRecords().stream().map(BizTopicResp::getId).collect(Collectors.toList());
        Map<Long, List<BizTopicResp>> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(parentIds)) {
            List<BizTopicResp> childList = baseMapper.listByParentIds(parentIds);
            map = childList.stream().collect(Collectors.groupingBy(BizTopicResp::getParentId));
        }
        for (int i = 0; i < page.getRecords().size(); i++) {
            BigDecimal indexNum = new BigDecimal(i + 1);
            page.getRecords().get(i).setIndexNum(indexNum);
            List<BizTopicResp> childList = map.get(page.getRecords().get(i).getId());
            if (!CollectionUtils.isEmpty(childList)) {
                for (int j = 0; j < childList.size(); j++) {
                    childList.get(j).setIndexNum(indexNum.add(BigDecimal.valueOf(j + 1).multiply(BigDecimal.valueOf(0.1))));
                }
                page.getRecords().get(i).setChildren(childList);
            }
        }
        return page;
    }

    public List<BizTopicResp> listByProjectIds(List<Long> projectIds) {
        List<BizTopicResp> result = new ArrayList<>();
        List<BizTopicResp> list = baseMapper.listByProjectIds(projectIds, isAll() ? "1" : getUserId() + "");
        result = list.stream().filter(item -> item.getParentId() == 0).collect(Collectors.toList());
        Map<Long, List<BizTopicResp>> map = list.stream().filter(r -> r.getParentId() != 0)
                .collect(Collectors.groupingBy(BizTopicResp::getParentId));
        Map<Long, BigDecimal> mapIndex = new HashMap<>();
        for (BizTopicResp p : result) {
            BigDecimal indexNum = mapIndex.getOrDefault(p.getProjectId(), BigDecimal.ONE);
            p.setIndexNum(indexNum);
            List<BizTopicResp> childList = map.get(p.getId());
            if (!CollectionUtils.isEmpty(childList)) {
                for (int j = 0; j < childList.size(); j++) {
                    childList.get(j).setIndexNum(indexNum.add(BigDecimal.valueOf(j + 1).multiply(BigDecimal.valueOf(0.1))));
                }
                p.setChildren(childList);
            }
            mapIndex.put(p.getProjectId(), indexNum.add(BigDecimal.ONE));
        }
        return result;
    }

    /**
     * 查询子课题列表
     */
    public List<BizTopicResp> list(BizTopicReq req) {
        req.getParams().put("userId", isAll() ? "1" : getUserId());
        return baseMapper.list(req);
    }

    /**
     * 根据ID查询
     */
    public BizTopicResp selectById(Long id) {
        BizTopicResp resp = baseMapper.selectDetail(id);
        String valStr = configService.selectConfigByKey("biz.topic.warning.days");
        if (valStr != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(resp.getEndTime());
            cal.add(Calendar.DAY_OF_MONTH, Integer.parseInt(valStr) * -1);
            resp.setWarnTime(cal.getTime());
        }
        return resp;
    }

    /**
     * 新增修改子课题
     */
    @Transactional(rollbackFor = Exception.class)
    public void beforeSave(BizTopic bizTopic) {
        if (bizTopic.getId() != null) {
            bizTopic.setUpdateTime(DateUtils.getNowDate());
        } else {
            bizTopic.setCreateTime(DateUtils.getNowDate());
            bizTopic.setUpdateTime(DateUtils.getNowDate());
            bizTopic.setUserId(getUserId());
            if (bizTopic.getParentId() == null) {
                bizTopic.setParentId(0L);
            }
        }
        saveOrUpdate(bizTopic);
    }

    @Transactional(rollbackFor = Exception.class)
    public void start(Long id) {
        BizTopic bizTopic = selectById(id);
        if (bizTopic == null) {
            throw new ServiceException("开始失败，请刷新页面重试");
        }
        bizTopic.setStatus(1);
        saveOrUpdate(bizTopic);
    }

    /**
     * 批量删除子课题
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteByIds(List<Long> ids) {
        //删除跟进
        LambdaQueryWrapper<BizTopicFollow> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(i -> i.in(BizTopicFollow::getTopicId, ids));
        bizTopicFollowMapper.delete(wrapper);
        //删除子级
        LambdaQueryWrapper<BizTopic> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.and(i -> i.in(BizTopic::getParentId, ids));
        baseMapper.delete(wrapper2);
        return baseMapper.deleteBatchIds(ids);
    }

}
